package com.itheima.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.bean.Category;
import com.itheima.reggie.bean.Dish;
import com.itheima.reggie.bean.DishFlavor;
import com.itheima.reggie.bean.SetmealDish;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 * User: 许志民
 * Date: 2021-11-24
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 保存菜品
     * @param dishDto
     */
    @Transactional
    @Override
    public void saveDishDto(DishDto dishDto) {
        save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long id = dishDto.getId();
        flavors.stream().forEach(s -> s.setDishId(id));
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<DishDto> findByPage(Integer page, Integer pageSize,String name) {

        IPage<Dish> dishIPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
        if(name!= null&& name != ""){
            wapper.like(Dish::getName,name);
        }
        wapper.orderByDesc(Dish::getUpdateTime);
        IPage<Dish> page1 = this.page(dishIPage, wapper);
        List<Dish> records = page1.getRecords();
        List<DishDto> dishDtos = JSON.parseArray(JSON.toJSONString(records), DishDto.class);
        for (DishDto dishDto : dishDtos) {
            Long categoryId = dishDto.getCategoryId();
            Category categoryServiceById = categoryService.getById(categoryId);
            dishDto.setCategoryName(categoryServiceById.getName());
        }
        Page<DishDto> dishDtoPage = new Page<>();
        dishDtoPage.setRecords(dishDtos);
        dishDtoPage.setTotal(page1.getTotal());
        return dishDtoPage;
    }

    /**
     * 修改前回显要修改的数据
     * @param id  根据id查询
     * @return
     */
    @Override
    public DishDto findById(Long id) {
        if(id == null){
            return null;
        }
        Dish byId = getById(id);
        LambdaQueryWrapper<DishFlavor> wapper = new LambdaQueryWrapper<>();
        wapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(wapper);
        DishDto dishDto = new DishDto();
        //方法二BeanUtils.copyProperties(复制对象，粘贴对象)
        dishDto = JSON.parseObject(JSON.toJSONString(byId),DishDto.class);
        dishDto.setFlavors(list);
        return dishDto;
    }

    /**
     *
     * @param dishDto
     * @return
     */
    @Transactional
    @Override
    public boolean updateBy(DishDto dishDto) {
        updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> wapper = new LambdaQueryWrapper<>();
        //先删除口味表中的对应数
        wapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wapper);
        wapper.clear();
        //再添加
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) ->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        boolean batch = dishFlavorService.saveBatch(flavors);
        return batch;
    }

    /**
     * 修改菜品单个状态或多个
     * @param status
     * @param id
     * @return
     */
    @Override
    public boolean updateStatus(Integer status, Long[] id) {
        if(status == null && id == null){
            return false;
        }
//        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
//        QueryWrapper<Dish> wapper = new QueryWrapper<>();
        UpdateWrapper<Dish> wapper = new UpdateWrapper<>();
//        for (Long aLong : id) {
//            wapper.eq("id",aLong).set("status",status);
//            update(wapper);
//        }

        List<Long> longs = Arrays.asList(id);
        wapper.in("id",longs).set("status",status);
        boolean update = update(wapper);

        return update;
    }

    /**
     * 单个删除或多个删除
     * @param ids
     * @return
     */
    @Override
    public boolean deleteids(Long[] ids) {
        //判断该菜品是否关联了相应的口味表
        List<Long> longs = Arrays.asList(ids);
        UpdateWrapper<DishFlavor> fWapper = new UpdateWrapper<>();
        fWapper.in("dish_id",longs);
        List<DishFlavor> list = dishFlavorService.list(fWapper);
        if(list != null){
            fWapper.set("is_deleted",1);
            dishFlavorService.update(fWapper);
        }
        UpdateWrapper<SetmealDish> suw = new UpdateWrapper<>();
        suw.in("dish_id",longs);

        List<SetmealDish> setmealDishList = setmealDishService.list(suw);
        if(setmealDishList != null){
            suw.set("is_deleted",1);
            setmealDishService.update(suw);
            log.info("修改了setmeal中的逻辑删除状态");
        }
        //最后修改dish表中的逻辑删除内容
        UpdateWrapper<Dish> dishWrapper = new UpdateWrapper<>();
        dishWrapper.in("id", longs).set("is_deleted", 1);
        boolean update = update(dishWrapper);
        return update;
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<DishDto> getList(Long id) {
//        List<DishDto> DishDto_List= (List<DishDto>) redisTemplate.opsForValue().get("DishDto_" + id);
//        if(DishDto_List != null && DishDto_List.size() != 0){
//            return DishDto_List;
//        }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,id);
        wrapper.eq(Dish::getStatus,1);
        List<Dish> list = this.list(wrapper);
        List<DishDto> dtoList = list.stream().map(item ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null){
                dishDto.setCategoryName(category.getName());
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());
//        redisTemplate.opsForValue().set("DishDto_" + id,dtoList);
        return dtoList;
    }
}
